
//
// 130724 - AH - (Paris) Created.
//

package org.bisonservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *   Servlet that test bison service TODO
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class RegisterBisonServlet extends HttpServlet
{
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    perform(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException 
  {
    perform(req, resp);
  }

  protected void perform(HttpServletRequest req,
    HttpServletResponse resp) throws ServletException, IOException 
  {
    String mime=req.getParameter("mime");
    mime=(mime==null) ? "" : mime.trim();
   
    String tmime=req.getParameter("tmime");
    tmime=(tmime==null) ? "" : tmime.trim();
    
    String[] ouridata=parseUriParams(req, "");
    String oscheme=ouridata[0];
    String opq=ouridata[1];
    
    String[] turidata=parseUriParams(req, "t");
    String tscheme=turidata[0];
    String tpq=turidata[1];
    
    String uri=makeUri(oscheme, opq);
    String turi=makeUri(tscheme, tpq);
    
    String[] regbison=null;
    if (uri.length()>0)
    {
      regbison=getBison(mime, uri, tmime, turi);
    }
    
    resp.setContentType("text/html");
    PrintWriter pw=resp.getWriter();
    
    pw.println("<html><body>");
    pw.println(getProse());
    pw.println("<form action='register-bison'>");
    
    // Original data input:
    
    pw.println("Original resource:<br/>");
    pw.println(
      "MIME (i.e. text/plain, text/xml, image/jpg...): <input type='text' name='mime'");
    if (mime.length()>0) pw.print(" value='"+mime+"'");
    pw.println("/><br/>");
    
    pw.print(
      "Scheme (i.e. this, http, ftp ...) : <input type='text' name='scheme'");
    if (oscheme.length()>0) pw.print(" value='"+oscheme+"'");
    pw.print("/>");
    
    pw.print(" Path / Query: <input type='text' name='pq'");
    if (opq.length()>0) pw.print(" value='"+opq+"'");
    pw.println("/><br/><br/>");
    
    // Transformed data input:
    
    pw.println("Transformed resource (optional):<br/>");
    pw.println("MIME (i.e. text/plain, text/xml, image/jpg...): <input type='text' name='tmime'");
    if (tmime.length()>0) pw.print(" value='"+tmime+"'");
    pw.println("/><br/>");
    
    pw.print(
      "Scheme (i.e. this, http, ftp ...) : <input type='text' name='tscheme'");
    if (tscheme.length()>0) pw.print(" value='"+tscheme+"'");
    pw.print("/>");
    
    pw.print(" Path / Query: <input type='text' name='tpq'");
    if (tpq.length()>0) pw.print(" value='"+tpq+"'");
    pw.println("/><br/>");
    
    pw.println("<input type='submit' value='Submit'>");
    
    pw.println("</form>");

    if (regbison!=null)
    {
      pw.println("<p>");
      pw.println("Bison registered: "+regbison[1]+"<br/>");
      pw.println("Registered used request: "+regbison[0]);
      pw.println("</p>");
      pw.println("</body></html>");
    }
  }
  
  private String[] getBison(String mime, String uri, String tmime, String turi)
    throws IOException
  {
    mime=(mime==null) ? "" : mime.trim();
    uri=(uri==null) ? "" : uri.trim();
    
    if (mime.length()==0 || uri.length()==0)
    {
      return new String[]{ "", "" };
    }
    
    String[] retVal=new String[2];
    
    tmime=(tmime==null) ? "" : tmime.trim();
    turi=(turi==null) ? "" : turi.trim();
	
    StringBuilder sb=
      new StringBuilder(
        "http://machinedeconversation.appspot.com/bison-service?oper=register");
	
    sb.append("&mime=").append(mime)
      .append("&uri=").append(uri);
	
    if (tmime.length()>0) sb.append("&tmime=").append(tmime);
    if (turi.length()>0)  sb.append("&turi=").append(turi);
	
    String req=sb.toString();
    retVal[0]=req;
	  
    URL url=new URL(req);    
	  
    InputStream is=url.openStream();
	
    BufferedReader br=new BufferedReader(new InputStreamReader(is));
    String reply=br.readLine();
    retVal[1]=reply;
    
    return retVal;
  }
  
  private static String[] parseUriParams(HttpServletRequest req, String pfix)
  {
    String scheme=req.getParameter(pfix+"scheme");
    String pq=req.getParameter(pfix+"pq");
    
    scheme=(scheme==null) ? "" : scheme.trim();
    pq=(pq==null) ? "" : pq.trim();
    
    String[] retVal=new String[2];
    retVal[0]=scheme;
    retVal[1]=pq;
    return retVal;
  }
  
  private static String makeUri(String scheme, String pq) throws IOException
  {
    scheme=(scheme==null) ? "" : scheme.trim();
    pq=(pq==null) ? "" : pq.trim();
    
    if (scheme.length()==0 && pq.length()==0) return "";
    
    scheme=(scheme.length()==0) ? "this" : scheme;
    
    if (scheme.equals("this")) pq=URLEncoder.encode(pq, "ISO-8859-1");
    
    StringBuilder sb=new StringBuilder();
    sb.append(scheme).append("://").append(pq);
    
    return sb.toString();
  }
  
  private static String getProse()
  {
    StringBuilder sb=new StringBuilder();
    sb.append("<h2>Bison</h2>");
    sb.append("<p>")
      .append("So what is a Bison? You can think of it as the next generation of semantic link. Actually it builds partly on what the 'link' utilizes, the URI. URL and URI aren't exactly like hyperlinks in our semantic paradigm; but they are pointers to a conversation's actions, like sounds, images, text, etc... Bisons are actions you find interesting to share through a conversation when the time is right. Conversations contribute to machines' meaningful exchanges of information.")
      .append("</p>")
      .append("<p>")
      .append("We build on internet standards which make our semantic technology compatible with our current digital realm. The standards are Multimedia type (MIME) and Unified Resource Identifer (URI). mime: format of action, type of resource. URI: identifier, typically the location of a conversation's action that has been digitalized. The form a bison is seen as text is mime:uri. Example: a bison can also itself represents the conversation's action. In that case, the mime type is text/plain, the URI scheme this and the reference part is the content itself. Example: text/plain:this:I+love+the+new+semantic+world")
      .append("</p>");
    return sb.toString();
  }
  
}
